package com.liwei.lwmail.product.web;

import com.liwei.lwmail.product.entity.CategoryEntity;
import com.liwei.lwmail.product.service.CategoryService;
import com.liwei.lwmail.product.vo.Catalog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 首页Controller
 */
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedissonClient redisson;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping({"/index.html","/"})
    public String indexPage(Model model){
        //TODO 查出所有的一级分类
        List<CategoryEntity> list = categoryService.getLevelOneList();
        model.addAttribute("cats",list);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    /**
     * 可重入锁
     * @return
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        //1、获取一把锁，指定锁的名字，锁名一样就代表是同一把锁
        RLock lock = redisson.getLock("my-lock");

        //2、加锁
        //lock.lock();//阻塞式等待
        lock.lock(10, TimeUnit.SECONDS);//10秒后自动解锁--一定要大于业务执行时间，不会自动续期
        try {
            System.out.println("加锁成功，执行业务");
            Thread.sleep(5000);
        }catch (Exception e){
            e.printStackTrace();
        } finally{
            //3、解锁
            System.out.println("释放锁");
            lock.unlock();
        }

        return "hello";
    }

    /**
     * 读写锁-写锁
     * @return
     */
    @ResponseBody
    @GetMapping("/write")
    public String write(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock wLock = lock.writeLock();//获取写锁
        String s = "";
        //加写锁
        wLock.lock();
        try {
            //写入数据
            s = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set("write",s);
            Thread.sleep(20000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //释放写锁
            wLock.unlock();
        }
        return s;
    }

    /**
     * 读写锁-读锁
     * @return
     */
    @ResponseBody
    @GetMapping("/read")
    public String read(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        RLock rLock = lock.readLock();//获取读锁
        String s ="";
        //加读锁
        rLock.lock();
        try {
            //读取数据
            s = redisTemplate.opsForValue().get("write");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放读锁
            rLock.unlock();
        }
        return s;
    }

    /**
     * 信号量
     * @return
     * @throws InterruptedException
     */
    @ResponseBody
    @GetMapping("/park")
    public String park() throws InterruptedException {
        RSemaphore semaphore = redisson.getSemaphore("park-lock");
        //semaphore.acquire();//获取一个信号,获取不到就一直等待
        boolean b = semaphore.tryAcquire();//尝试获取。获取不到就算了
        return "ok=>"+b;
    }
    @ResponseBody
    @GetMapping("/go")
    public String go() throws InterruptedException {
        RSemaphore semaphore = redisson.getSemaphore("park-lock");
        semaphore.release();//释放一个信号
        return "ok";
    }

    /**
     * 闭锁
     * @return
     */
    @ResponseBody
    @GetMapping("/lockDoor")
    public String lockDoor() throws InterruptedException {
        RCountDownLatch downLatch = redisson.getCountDownLatch("door-lock");
        downLatch.trySetCount(5);//设置需等待的数目
        downLatch.await();//等待闭锁都完成，执行下一步
        return "放假啦。。。。";
    }

    @ResponseBody
    @GetMapping("/go/{id}")
    public String go(@PathVariable("id") Long id){
        RCountDownLatch downLatch = redisson.getCountDownLatch("door-lock");
        downLatch.countDown();//计数-1
        return id+"班的人走了";
    }
}
